﻿using Autofac;
using CSRedis;
using EventBusETO.CustomerType;
using EventBusETO.DataStatistics;
using EventBusETO.RoomType;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using SH.Common;
using SH.Common.CommonReturn;
using SH.Multitenant.Application.IServices.IDic;
using SH.Multitenant.Application.IServices.IStatistics;
using SH.Multitenant.Application.Services;
using SqlSugar;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Configuration;

namespace SH.Multitenant.API.Controllers
{
    /// <summary>
    /// 数据统计API
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]

    public class DataStatisticsController : ControllerBase
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly CSRedisClient _redis = AppService.AutofacContainer.Resolve<CSRedisClient>();
        private readonly IDicServices _dicServices;
        /// <summary>
        /// 构造方法注入
        /// </summary>
        /// <param name="httpClientFactory"></param>
        public DataStatisticsController(IHttpClientFactory httpClientFactory, IDicServices dicServices)
        {
            _httpClientFactory = httpClientFactory;
            _dicServices = dicServices;
        }
        #region 初始页统计
        private const string Customers = "http://119.3.224.52:9999/api/Customer/GetAllCustomers";
        private const string RoomTypes = "http://1.92.78.23:9003/api/RoomType/GetRoomList";
        private const string Orders = "http://121.36.38.27:9033/api/OrderInfo/GetAllOrders";
        /// <summary>
        /// 取消订单数和实收款
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetOrderCountsandActualReceives()
        {
            ApiResult<StatisticsDTO<GroupDTO>> apiResult = new ApiResult<StatisticsDTO<GroupDTO>>();
            var client = _httpClientFactory.CreateClient();
            //订单
            var order = client.GetAsync(Orders).Result;
            //字典
            var diclist = _dicServices.All.ToList();
            //客户
            var customer = client.GetAsync(Customers).Result;
            //房型
            var roomType = client.GetAsync(RoomTypes).Result;

            //自定义时间区间 这里显示本月
            StatisticsDTO<GroupDTO> groupList = new StatisticsDTO<GroupDTO>();
            groupList.StartTime = DateTime.Parse(DateTime.Now.ToString("yyyy-01-01"));
            groupList.EndTIme = DateTime.Now;
            //如果成功
            if (order.IsSuccessStatusCode && customer.IsSuccessStatusCode && roomType.IsSuccessStatusCode)
            {
                //获取当前租户
                string tenantId = _redis.Get<string>("tenantId");
                //存Redis
                var list = _redis.HGet<List<OrderETO>>("statisticsList", tenantId);
                if (list != null && list.Count() > 0)
                {

                }
                else
                {
                    //客户
                    var customerMessage = customer.Content.ReadAsStringAsync().Result;
                    var customerList = JsonConvert.DeserializeObject<List<CustomerEto>>(customerMessage);
                    //房型
                    var roomTypeMessage = roomType.Content.ReadAsStringAsync().Result;
                    var roomTypeList = JsonConvert.DeserializeObject<List<RoomTypeEto>>(roomTypeMessage);
                    var orderMessage = order.Content.ReadAsStringAsync().Result;
                    var orderList = JsonConvert.DeserializeObject<List<OrderInfoETO>>(orderMessage);
                    list = (from a in orderList
                            join b in customerList on a.CoustomerId equals b.CId
                            join c in roomTypeList on a.RTId equals c.Rtid
                            join d in diclist on a.OrderStatus equals d.Id
                            select new OrderETO
                            {
                                OrderNo = a.OrderNo,
                                Rtname = c.Rtname,
                                CName = b.CName,
                                OrderType = a.OrderType,
                                Tel = b.Tel,
                                CId = b.CId,
                                EntryTime = a.EntryTime,
                                LeaveTime = a.LeaveTime,
                                ActualPay = c.Rprice,
                                OrderStatus = d.Id,
                                value = d.Value,
                                Id = a.Id,
                                OrderTime = a.OrderTime,
                                Rtid = c.Rtid,
                                IsDelete = a.IsDelete,
                                PayMode = a.PayMode,
                                RTId = c.Rtid,

                            }).ToList();
                    _redis.HSet("statisticsList", tenantId, list);
                    _redis.Expire("statisticsList", 120);//如果数据更新则清除该key值
                }
                groupList.Data = (from a in list
                                  where a.EntryTime >= groupList.StartTime && a.EntryTime < groupList.EndTIme
                                  orderby a.EntryTime
                                  group a by a.EntryTime.ToString("yyyy-MM") into b
                                  select new GroupDTO
                                  {
                                      DateFormat = b.Key,
                                      CancelOrderCount = b.Count(x => !x.IsDelete),
                                      ActualReceives = b.Sum(x => x.ActualPay)
                                  }).ToList() ?? new List<GroupDTO>();
                apiResult.Success(groupList);
            }
            else
            {
                apiResult.Error(ApiResult<StatisticsDTO<GroupDTO>>.ErrorType.Service, "访问订单api错误");
            }
            return Ok(apiResult);
        }

        /// <summary>
        /// 热点房型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetHotRoomTypes()
        {
            ApiResult<StatisticsDTO<HotRoomType>> apiResult = new ApiResult<StatisticsDTO<HotRoomType>>();
            var client = _httpClientFactory.CreateClient();
            //订单
            var order = client.GetAsync(Orders).Result;
            //字典
            var diclist = _dicServices.All.ToList();
            //客户
            var customer = client.GetAsync(Customers).Result;
            //房型
            var roomType = client.GetAsync(RoomTypes).Result;

            //自定义时间区间 这里显示本月
            StatisticsDTO<HotRoomType> groupList = new StatisticsDTO<HotRoomType>();
            groupList.StartTime = DateTime.Parse(DateTime.Now.ToString("yyyy-01-01"));
            groupList.EndTIme = DateTime.Now;
            if (order.IsSuccessStatusCode && customer.IsSuccessStatusCode && roomType.IsSuccessStatusCode)
            {
                //获取当前租户
                string tenantId = _redis.Get<string>("tenantId");
                //存Redis
                var list = _redis.HGet<List<OrderETO>>("statisticsList", tenantId);
                if (list != null && list.Count() > 0)
                {

                }
                else
                {
                    //客户
                    var customerMessage = customer.Content.ReadAsStringAsync().Result;
                    var customerList = JsonConvert.DeserializeObject<List<CustomerEto>>(customerMessage);
                    //房型
                    var roomTypeMessage = roomType.Content.ReadAsStringAsync().Result;
                    var roomTypeList = JsonConvert.DeserializeObject<List<RoomTypeEto>>(roomTypeMessage);
                    var orderMessage = order.Content.ReadAsStringAsync().Result;
                    var orderList = JsonConvert.DeserializeObject<List<OrderInfoETO>>(orderMessage);
                    list = (from a in orderList
                            join b in customerList on a.CoustomerId equals b.CId
                            join c in roomTypeList on a.RTId equals c.Rtid
                            join d in diclist on a.OrderStatus equals d.Id
                            select new OrderETO
                            {
                                OrderNo = a.OrderNo,
                                Rtname = c.Rtname,
                                CName = b.CName,
                                OrderType = a.OrderType,
                                Tel = b.Tel,
                                CId = b.CId,
                                EntryTime = a.EntryTime,
                                LeaveTime = a.LeaveTime,
                                ActualPay = c.Rprice,
                                OrderStatus = d.Id,
                                value = d.Value,
                                Id = a.Id,
                                OrderTime = a.OrderTime,
                                Rtid = c.Rtid,
                                IsDelete = a.IsDelete,
                                PayMode = a.PayMode,
                                RTId = c.Rtid,

                            }).ToList();
                    _redis.HSet("statisticsList", tenantId, list);
                    _redis.Expire("statisticsList", 120);//如果数据更新则清除该key值
                }
                //按月统计热点房型
                groupList.Data = (from a in list
                                  where a.IsDelete && a.EntryTime >= groupList.StartTime && a.EntryTime < groupList.EndTIme
                                  orderby a.EntryTime
                                  group a by new { a.RTId, a.Rtname } into b
                                  select new HotRoomType
                                  {
                                      RoomTypeName = b.Key.Rtname,
                                      RoomTypeCount = b.Count(),
                                  }).ToList() ?? new List<HotRoomType>();
                apiResult.Success(groupList);
            }
            else
            {
                apiResult.Error(ApiResult<StatisticsDTO<HotRoomType>>.ErrorType.Service, "访问订单api错误");
            }
            return Ok(apiResult);
        }
        #endregion
    }
}
